#include "app_oled.h"
#include "app_log.h"
#include "cmsis_os2.h"
#include "ohos_init.h"
#include "stdbool.h"
#include "app_env.h"
#include "mutex.h"

const static char *TAG = "app_oled.c";

#define OLED_DELAY_50MS 5

static void oled_main_interface(uint8_t threshold, env_data *data, env_ctrl_status *status)
{
    char str[10] = "";
    struct oled_data
    {
        float Lux;         // 光照强度
        float Humidity;    // 湿度
        float Temperature; // 温度
    };
    struct oled_data oled_show_data;

    osMutexAcquire(env_mutexId, osWaitForever); /* 获取环境数据互斥锁 */
    oled_show_data.Lux = data->Lux;
    oled_show_data.Humidity = data->Humidity;
    oled_show_data.Temperature = data->Temperature;
    osMutexRelease(env_mutexId); /* 释放环境数据互斥锁 */

    /* 显示温湿度、光照强度、风扇状态 */
    GUI_ShowCHinese_UTF(0, 0, 16, "温度", 1);
    sprintf(str, ":%.1f C", oled_show_data.Temperature);
    GUI_ShowString(32, 0, str, 16, 1);
    GUI_ShowCHinese_UTF(0, 16, 16, "湿度", 1);
    sprintf(str, ":%.1f %%", oled_show_data.Humidity);
    GUI_ShowString(32, 16, str, 16, 1);
    GUI_ShowCHinese_UTF(0, 32, 16, "光照", 1);
    sprintf(str, ":%.1f lx", oled_show_data.Lux);
    GUI_ShowString(32, 32, str, 16, 1);
    GUI_ShowCHinese_UTF(0, 48, 16, "风扇", 0);
    if (status->fan == 1)
        GUI_ShowString(30, 48, ":ON ", 16, 0);
    else
        GUI_ShowString(30, 48, ":OFF", 16, 0);
    GUI_ShowCHinese_UTF(62, 48, 16, "灯", 0);
    if (status->light == 1)
        GUI_ShowString(76, 48, ":ON ", 16, 0);
    else
        GUI_ShowString(76, 48, ":OFF", 16, 0);

    /* 显示阈值和组名称 */
    sprintf(str, "%d", threshold);
    GUI_ShowString(110, 0, str, 16, 1);
    GUI_ShowCHinese_UTF(110, 16, 16, "第", 0);
    GUI_ShowCHinese_UTF(110, 32, 16, "五", 0);
    GUI_ShowCHinese_UTF(110, 48, 16, "组", 0);
}

/**
 * @brief oled_test_task
 */
void oled_test_task(void)
{
    MY_LOGI(TAG, "Start OLED Init \r\n");
    OLED_Init_GPIO(); /* 初始化OLED引脚 */
    OLED_Init();      /* 初始化OLED */
    OLED_Clear(0);    /* 清屏（全黑-0）*/
    while (1)
    {
        OLED_Display();
        oled_main_interface(MAX_HUM_ONE, &app_env_data, &app_env_ctrl_status); /* 显示主界面 */
        osDelay(OLED_DELAY_50MS);
    }
}
